﻿using System;
using System.IO.Ports;

namespace SerialPortModel
{
    public delegate void DataReceived(object sender, SerialDataReceivedEventArgs e);
    public class CSerialPortModel
    {
        private readonly SerialPort com;
        public CSerialPortModel(string portName, int baudRate, int dataBits, Parity parity, StopBits stopBits)
        {
            com = new SerialPort
            {
                BaudRate = baudRate,
                PortName = portName,
                DataBits = dataBits,
                StopBits = stopBits,
                Parity = parity
            };
        }

        public void SetDataReceived(DataReceived dataReceived)
        {
            com.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
        }

        public void SendData(byte[] TxData)
        {
            com.Write(TxData, 0, TxData.Length);
        }

        public bool Open()
        {
            try
            {
                if (com.IsOpen)
                {
                    com.Close();
                }

                if (!com.IsOpen)
                {
                    com.Open();
                }

                return true;
            }
            catch (Exception)
            {
            }
            return false;
        }
        public void Close()
        {
            if (com.IsOpen)
            {
                com.Close();
            }
        }
        public bool IsOpen()
        {
            return com.IsOpen;
        }
    }
}
